package com.cherry.sdk.http.json

import com.cherry.sdk.http.response.ResponseConfig
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken

/**
 * @author 董棉生(dongmiansheng@parkingwang.com)
 * @since 18-11-16
 */

object Json {

    private lateinit var responseConfig: ResponseConfig

    /**
     * 开放Builder配置
     */
    val GSON_BUILDER by lazy {
        val builder = GsonBuilder().setPrettyPrinting()

        responseConfig.typeAdapterFactoryList?.let {
            for (item in it) {
                builder.registerTypeAdapterFactory(item)
            }
        }

        responseConfig.typeAdapterMap?.let {
            for (item in it) {
                builder.registerTypeAdapter(item.key, item.value)
            }
        }
        builder
    }

    val GSON by lazy {
        GSON_BUILDER.create()
    }


    internal fun init(responseConfig: ResponseConfig): Json {
        this.responseConfig = responseConfig
        return this
    }


    fun <T> parseArray(json: String, cls: Class<T>): ArrayList<T> {
        val type = TypeToken.getParameterized(ArrayList::class.java, cls).type
        return GSON.fromJson<ArrayList<T>>(json, type) ?: arrayListOf()
    }

    fun <T> parseObject(json: String, cls: Class<T>): T? {
        return GSON.fromJson(json, cls)
    }

    fun <T> toJson(obj: T): String {
        return GSON.toJson(obj)
    }
}

